import 'package:flutter/material.dart';

class NoKeyDemo extends StatefulWidget {
  final String title;

  const NoKeyDemo({super.key, required this.title});

  @override
  State<NoKeyDemo> createState() => _NoKeyDemoState();
}

class _NoKeyDemoState extends State<NoKeyDemo> {
  late List<Widget> titles;

  @override
  void initState() {
    super.initState();
    titles = [
      StfCardWidget(
          title: 'CardA', color: Colors.red, key: const ValueKey('CardA')),
      StfCardWidget(
          title: 'CardB', color: Colors.green, key: const ValueKey('CardB')),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Column(
        children: titles,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            titles.insert(1, titles.removeAt(0));
          });
        },
        child: const Icon(Icons.swap_vert),
      ),
    );
  }
}

// widget
class StfCardWidget extends StatefulWidget {
  final String title;
  final Color color;

  StfCardWidget({super.key, required this.title, required this.color});

  @override
  StatefulElement createElement() {
    // TODO: implement createElement
    print('JtTag:节点hashCode:${this.hashCode}');
    return super.createElement();
  }

  @override
  State<StfCardWidget> createState() => _StfCardWidgetState();
}

// 存放状态
class _StfCardWidgetState extends State<StfCardWidget> {
  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return Card(
      color: widget.color,
      child: ListTile(
        title: Text(widget.title),
        subtitle: Text('我是 ${widget.title}，点击次数：$counter'),
        trailing: IconButton(
          icon: const Icon(Icons.add),
          onPressed: () => setState(() {
            counter++;
          }),
        ),
      ),
    );
  }
}
